/**
 * 工具提示指令 - 用于在元素上显示悬浮提示
 */
export function useTooltip() {
  // 当前激活的提示 
  let activeTooltip = null;
  
  // 创建工具提示DOM元素
  const createTooltipElement = (content, theme = 'dark') => {
    const tooltip = document.createElement('div');
    tooltip.classList.add('v-tooltip');
    tooltip.classList.add(`v-tooltip-${theme}`);
    tooltip.innerHTML = content;
    
    // 添加复制按钮
    const copyButton = document.createElement('button');
    copyButton.textContent = '复制';
    copyButton.classList.add('v-tooltip-copy-btn');
    copyButton.addEventListener('click', (e) => {
      e.stopPropagation();
      try {
        navigator.clipboard.writeText(content);
        // 显示复制成功提示
        const successTip = document.createElement('span');
        successTip.textContent = '已复制';
        successTip.classList.add('v-tooltip-copy-success');
        copyButton.appendChild(successTip);
        
        setTimeout(() => {
          if (successTip.parentNode) {
            successTip.parentNode.removeChild(successTip);
          }
        }, 2000);
      } catch (error) {
        console.error('复制失败:', error);
      }
    });
    
    tooltip.appendChild(copyButton);
    document.body.appendChild(tooltip);
    return tooltip;
  };
  
  // 定位工具提示
  const positionTooltip = (tooltip, el, position = 'top') => {
    const rect = el.getBoundingClientRect();
    const scrollTop = window.scrollY || document.documentElement.scrollTop;
    const scrollLeft = window.scrollX || document.documentElement.scrollLeft;
    
    const elTop = rect.top + scrollTop;
    const elLeft = rect.left + scrollLeft;
    const elWidth = rect.width;
    const elHeight = rect.height;
    
    const tooltipHeight = tooltip.offsetHeight;
    const tooltipWidth = tooltip.offsetWidth;
    
    let top, left;
    
    switch (position) {
      case 'top':
        top = elTop - tooltipHeight - 10;
        left = elLeft + (elWidth / 2) - (tooltipWidth / 2);
        break;
      case 'bottom':
        top = elTop + elHeight + 10;
        left = elLeft + (elWidth / 2) - (tooltipWidth / 2);
        break;
      case 'left':
        top = elTop + (elHeight / 2) - (tooltipHeight / 2);
        left = elLeft - tooltipWidth - 10;
        break;
      case 'right':
        top = elTop + (elHeight / 2) - (tooltipHeight / 2);
        left = elLeft + elWidth + 10;
        break;
      default:
        top = elTop - tooltipHeight - 10;
        left = elLeft + (elWidth / 2) - (tooltipWidth / 2);
    }
    
    // 保证提示不超出视口
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;
    
    if (left < 10) left = 10;
    if (left + tooltipWidth > viewportWidth - 10) {
      left = viewportWidth - tooltipWidth - 10;
    }
    
    if (top < 10) top = 10;
    if (top + tooltipHeight > viewportHeight - 10) {
      top = viewportHeight - tooltipHeight - 10;
    }
    
    tooltip.style.top = `${top}px`;
    tooltip.style.left = `${left}px`;
  };
  
  // 显示工具提示
  const showTooltip = (el, config) => {
    if (activeTooltip) {
      hideTooltip();
    }
    
    if (config.disabled) return;
    
    const { content, position, theme, hideOnClick } = config;
    
    if (!content) return;
    
    const tooltip = createTooltipElement(content, theme);
    positionTooltip(tooltip, el, position);
    
    // 添加淡入效果
    setTimeout(() => {
      tooltip.classList.add('v-tooltip-active');
    }, 10);
    
    activeTooltip = tooltip;
    
    // 点击文档其他区域时隐藏提示
    if (hideOnClick) {
      const handleClickOutside = (event) => {
        if (el !== event.target && !el.contains(event.target)) {
          hideTooltip();
          document.removeEventListener('click', handleClickOutside);
        }
      };
      
      document.addEventListener('click', handleClickOutside);
    }
  };
  
  // 隐藏工具提示
  const hideTooltip = () => {
    if (activeTooltip) {
      activeTooltip.classList.remove('v-tooltip-active');
      
      // 等待过渡效果完成后删除元素
      setTimeout(() => {
        if (activeTooltip && activeTooltip.parentNode) {
          activeTooltip.parentNode.removeChild(activeTooltip);
        }
        activeTooltip = null;
      }, 300);
    }
  };
  
  // Vue指令
  const vTooltip = {
    mounted(el, binding) {
      const config = binding.value || {};
      let timer = null;
      
      // 默认值
      const defaultConfig = {
        content: '',
        position: 'top',
        theme: 'dark',
        delay: 200,
        hideOnClick: true,
        disabled: false
      };
      
      // 合并配置
      const mergedConfig = { ...defaultConfig, ...config };
      
      // 鼠标进入显示提示
      el.addEventListener('mouseenter', () => {
        if (mergedConfig.disabled) return;
        
        if (timer) clearTimeout(timer);
        
        timer = setTimeout(() => {
          showTooltip(el, mergedConfig);
        }, mergedConfig.delay);
      });
      
      // 鼠标离开隐藏提示
      el.addEventListener('mouseleave', () => {
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        
        hideTooltip();
      });
      
      // 保存配置到元素上
      el._tooltip_config = mergedConfig;
    },
    
    updated(el, binding) {
      // 更新配置
      const config = binding.value || {};
      el._tooltip_config = { ...el._tooltip_config, ...config };
    },
    
    unmounted(el) {
      // 清理
      hideTooltip();
    }
  };
  
  return { vTooltip };
}

// 添加全局样式
if (typeof document !== 'undefined') {
  const style = document.createElement('style');
  style.textContent = `
    .v-tooltip {
      position: absolute;
      z-index: 9999;
      padding: 8px 12px;
      font-size: 14px;
      border-radius: 4px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      max-width: 300px;
      word-break: break-word;
      pointer-events: all;
      opacity: 0;
      transition: opacity 0.3s;
    }
    
    .v-tooltip-active {
      opacity: 1;
    }
    
    .v-tooltip-dark {
      background-color: rgba(0, 0, 0, 0.75);
      color: white;
    }
    
    .v-tooltip-light {
      background-color: white;
      color: #333;
      border: 1px solid #eee;
    }
    
    .v-tooltip-copy-btn {
      display: block;
      margin-top: 8px;
      padding: 4px 8px;
      background: transparent;
      border: 1px solid #ccc;
      border-radius: 2px;
      color: inherit;
      font-size: 12px;
      cursor: pointer;
      position: relative;
    }
    
    .v-tooltip-copy-btn:hover {
      background-color: rgba(255, 255, 255, 0.1);
    }
    
    .v-tooltip-copy-success {
      position: absolute;
      right: -40px;
      top: 4px;
      font-size: 12px;
      color: #52c41a;
    }
  `;
  document.head.appendChild(style);
}

export default {
  install(app) {
    const { vTooltip } = useTooltip();
    app.directive('tooltip', vTooltip);
  }
}; 